package logics 
{
	import constants.Events;
	import constants.utils;
	import flash.events.Event;
	import structures.Structure;

	/**
	 * ...
	 * @author parasitic
	 */
	
	 
	 public class UnitFactory extends Logic 
	{
		private var types:Array;
		
		private function getUnitFromIndex(i:int):Structure
		{
			try
			{
				var unitClass:Class = getClassFromIndex(i); 
				return new unitClass();
			}
			catch (err:Error)
			{
				trace("getUnitFromIndex: " + err);
			}
			
			return null;
		}
		
		private function getClassFromIndex(i:int):Class
		{
			try
			{
				return types[i];
			}
			catch (err:Error)
			{
				trace("getClassFromIndex: " + err);
			}
			
			return null;
		}
		
		private function checkIndex(index:int):Boolean
		{
			return index < types.length;
		}
		
		public function addType(c:Class):void
		{
			try
			{
				if (c.prototype instanceof Structure)
				{
					types.push(c);
				}
			}
			catch (err:Error)
			{
				trace("addType: " + err);
			}
		}
		
		private function startbuild_handler(e:CustomEvent):void
		{	
			try 
			{
				//get index of building type from event dispatch
				var index:int = e.args;
				
				if (checkIndex(index))
				{
					var struct:Structure = getUnitFromIndex(index);
					struct.startBuild();
					dispatchEvent(new CustomEvent(Events.NOW_BUILDING, struct));
				}
			}
			catch (err:Error)
			{
				trace("startbuild_handler: " + err);
			}
		}
		
		private function finishbuild_handler(e:CustomEvent):void
		{
			try
			{
				var struct:Structure = e.args;
				struct.stopBuild();
				dispatchEvent( new CustomEvent(Events.SET_FREE));
			}
			catch (err:Error)
			{
				trace("finishbuild_handler: " + err);
			}
		}
		
		override protected function init(e:Event):void
		{
			super.init(e);
			types = new Array();
			
			newListener(Events.START_BUILD, startbuild_handler);
			newListener(Events.FINISH_BUILD, finishbuild_handler);
		}
		
		public function UnitFactory(s:StateMachine) 
		{
			super(s);
		}
		
	}

}